#include <iostream>
#include <string>
#include <strings.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>

struct ThreadData
{
    int sockfd;
    struct sockaddr_in server;
};

void* recv_msg(void* argc)
{
    ThreadData* td = static_cast<ThreadData*>(argc);
    char inbuffer[1024];
    while(1)
    {
        struct sockaddr_in tmp;
        socklen_t len = sizeof(tmp);

        ssize_t n = recvfrom(td->sockfd, inbuffer, sizeof(inbuffer) - 1, 0, (struct sockaddr*)&tmp, &len);
        if(n > 0)
        {
            inbuffer[n] = '\0';
            std::cerr << inbuffer << std::endl;
        }

    }
}

void* send_msg(void* argc)
{
    ThreadData* td = static_cast<ThreadData*>(argc);
    std::string outbuffer;
    while(1)
    {
        std::cout << "Please Enter# ";
        std::getline(std::cin, outbuffer);

        sendto(td->sockfd, outbuffer.c_str(), outbuffer.size(), 0, (struct sockaddr*)&(td->server), sizeof(td->server));
    }

}

void usage(std::string proc)
{
    std::cout << "\n\rUsage : " << proc << "ServerIp ServerPort\n" << std::endl; 
}
int main(int argc, char* argv[])
{
    if(argc != 3)
    {
        usage(argv[0]);
        exit(0);
    }

    uint16_t server_port = std::stoi(argv[2]);
    std::string server_ip = argv[1];

    ThreadData td;
    bzero(&td.server, sizeof(td.server));
    td.server.sin_family = AF_INET;
    td.server.sin_port = htons(server_port);    // 网络数据用大端
    td.server.sin_addr.s_addr = inet_addr(server_ip.c_str());

    // 创建套接字
    td.sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if(td.sockfd < 0)
    {
        std::cout << "socket fail" << std::endl;
        return 1;
    }
    // 绑定套接字
    // client 也需要绑定套接字，但是不需要用户显示绑定，os会随机分配
    
    pthread_t recv, send;
    pthread_create(&recv, nullptr, recv_msg, &td);
    pthread_create(&send, nullptr, send_msg, &td);


    pthread_join(recv, nullptr);
    pthread_join(send, nullptr);

    // std::string outbuffer;
    // char inbuffer[1024];
    // while(1)
    // {
    //     std::cout << "Please Enter@ ";
    //     getline(std::cin, outbuffer);
    //     //std::cout << outbuffer << std::endl;
        
    //     //发送数据到server
    //     sendto(sockfd, outbuffer.c_str(), outbuffer.size(), 0, (struct sockaddr*)&server, sizeof(server));


    //     // 接收数据
    //     struct sockaddr_in tmp;
    //     socklen_t len = sizeof(tmp);

    //     ssize_t n = recvfrom(sockfd, inbuffer, sizeof(inbuffer) - 1, 0, (struct sockaddr*)&tmp, &len);
    //     if(n > 0)
    //     {
    //         inbuffer[n] = '\0';
    //         std::cout << inbuffer << std::endl;
    //     }
        
    // }

    close(td.sockfd);

    return 0;
}